import { BasicDrawer, useDrawerInner } from "@/components/Drawer";
import { Avatar, Button, Popover, Tabs, Input, Form, message, Select, Tag } from "antd";
import { todoApi } from "@/api/bpm/task/todo";
import "./index.less";
import ApprovalDetails from "./components/approvalDetails/index";
import CirculationRecord from "./components/circulationRecord/index";
import { useEffect, useState } from "react";
import { formatDate } from "@/utils/util";
import { useTranslation } from "react-i18next";
import ProcessViewer from "@/components/bpmnProcessDesigner/package/designer/ProcessViewer";
import Icon from "@/components/Icon";
const { TextArea } = Input;
const { Item } = Form;

let page: String;
const index = (props: any) => {
	const { t } = useTranslation();
	const en_vi = "task.todo";
	const [process, setProcess] = useState<any>({});
	const [record, setRecord] = useState<any>(null);
	const [options, setOptions] = useState<any>([]);
	const [passThroughout, setPassThroughout] = useState<any>(false);
	const [refuse, setRefuse] = useState<any>(false);
	const [makeCopyFor, setMakeCopyFor] = useState<any>(false);
	const [transferOffice, setTransferOfficer] = useState<any>(false);
	const [delegateOpen, setDelegateOpen] = useState<any>(false);
	const [countersignOpen, setCountersignOpen] = useState<any>(false);
	// const [returnOpen, setReturnOpen] = useState<any>(false);
	const [cancelOpen, setCancelOpen] = useState<any>(false);
	const [taskListByProcess, setTaskListByProcess] = useState([]);
	const items = [
		{
			label: t(`${en_vi}.approvalDetails`),
			key: "1",
			children: <ApprovalDetails record={process} taskListByProcess={taskListByProcess}></ApprovalDetails>
		},
		{
			label: t(`${en_vi}.flowChart`),
			key: "2",
			children: (
				<div className="h-500px">
					<ProcessViewer xml={process.bpmnXml} view={process} />
				</div>
			)
		},
		{
			label: t(`${en_vi}.circulationRecord`),
			key: "3",
			children: <CirculationRecord taskListByProcess={taskListByProcess}></CirculationRecord>
		}
	];
	const [registerDrawer, { closeDrawer }] = useDrawerInner(props.register, data => {
		page = data.page;
		setRecord(data.record);
	});
	const pageButton = () => {
		switch (page) {
			case "todo":
				return (
					<div className="handlingProcess_button flex">
						<Popover content={() => content(1)} trigger="click" open={passThroughout} onOpenChange={handlePassThroughout}>
							<Button type="primary">{t(`${en_vi}.passThrough`)}</Button>
						</Popover>
						<Popover content={() => content(2)} trigger="click" open={refuse} onOpenChange={handleRefuse}>
							<Button danger>{t(`${en_vi}.refuse`)}</Button>
						</Popover>
						<Popover content={() => content(3)} trigger="click" open={makeCopyFor} onOpenChange={handleMakeCopyFor}>
							<Button type="text">{t(`${en_vi}.copy`)}</Button>
						</Popover>
						<Popover content={() => content(4)} trigger="click" open={transferOffice} onOpenChange={handleTransferOfficer}>
							<Button type="text">{t(`${en_vi}.transferOffice`)}</Button>
						</Popover>
						<Popover content={() => content(5)} trigger="click" open={delegateOpen} onOpenChange={handleDelegateOpen}>
							<Button type="text">{t(`${en_vi}.delegate`)}</Button>
						</Popover>
						<Popover content={() => content(6)} trigger="click" open={countersignOpen} onOpenChange={handleCountersignOpen}>
							<Button type="text">{t(`${en_vi}.countersign`)}</Button>
						</Popover>
						<Button type="text" onClick={onFinishReturnOpen}>
							{t(`${en_vi}.return`)}
						</Button>
						{/* <Popover content={() => content(8)} trigger="click" open={cancelOpen} onOpenChange={handleCancelOpen}>
						<Button type="text">取消</Button>
					</Popover> */}
					</div>
				);
			case "copy":
				return (
					<div className="handlingProcess_button flex">
						<Popover content={() => content(8)} trigger="click" open={cancelOpen} onOpenChange={handleCancelOpen}>
							<Button type="text">{t(`${en_vi}.cancel`)}</Button>
						</Popover>
					</div>
				);
			case "processInstance":
				return (
					<div className="handlingProcess_button flex">
						<Popover content={() => content(8)} trigger="click" open={cancelOpen} onOpenChange={handleCancelOpen}>
							<Button type="text">{t(`${en_vi}.cancel`)}</Button>
						</Popover>
					</div>
				);
			default:
				break;
		}
	};
	const content = (parameter: number) => {
		switch (parameter) {
			case 1:
				return (
					<div className="handlingProcess_button_Popover">
						<Form onFinish={onFinishPassThroughout} layout="vertical">
							<Item label={t(`${en_vi}.approvalOpinion`)} name="reason" rules={[{ required: true }]}>
								<TextArea rows={4} />
							</Item>
							<Item className="button">
								<Button type="primary" htmlType="submit">
									{t(`${en_vi}.agreeWith`)}
								</Button>
								<Button onClick={cancel}>{t(`${en_vi}.cancel`)}</Button>
							</Item>
						</Form>
					</div>
				);
			case 2:
				return (
					<div className="handlingProcess_button_Popover">
						<Form onFinish={onFinishRefuse} layout="vertical">
							<Item label={t(`${en_vi}.approvalOpinion`)} name="reason" rules={[{ required: true }]}>
								<TextArea rows={4} />
							</Item>
							<Item className="button">
								<Button type="primary" danger htmlType="submit">
									{t(`${en_vi}.refuse`)}
								</Button>
								<Button onClick={cancel}>{t(`${en_vi}.cancel`)}</Button>
							</Item>
						</Form>
					</div>
				);
			case 3:
				return (
					<div className="handlingProcess_button_Popover">
						<Form onFinish={onFinishMakeCopyFor} layout="vertical">
							<Item label={t(`${en_vi}.ccTo`)} name="copyUserIds" rules={[{ required: true }]}>
								<Select mode="multiple" allowClear style={{ width: "100%" }} placeholder="Please select" options={options} />
							</Item>
							<Item label={t(`${en_vi}.ccSuggestion`)} name="reason" rules={[{ required: true }]}>
								<TextArea rows={4} />
							</Item>
							<Item className="button">
								<Button type="primary" htmlType="submit">
									{t(`${en_vi}.copy`)}
								</Button>
								<Button onClick={cancel}>{t(`${en_vi}.cancel`)}</Button>
							</Item>
						</Form>
					</div>
				);
			case 4:
				return (
					<div className="handlingProcess_button_Popover">
						<Form onFinish={onFinishTransferOfficer} layout="vertical">
							<Item label={t(`${en_vi}.newApprover`)} name="assigneeUserId" rules={[{ required: true }]}>
								<Select style={{ width: "100%" }} options={options} />
							</Item>
							<Item label={t(`${en_vi}.approvalOpinion`)} name="reason" rules={[{ required: true }]}>
								<TextArea rows={4} />
							</Item>
							<Item className="button">
								<Button type="primary" htmlType="submit">
									{t(`${en_vi}.transferOffice`)}
								</Button>
								<Button onClick={cancel}>{t(`${en_vi}.cancel`)}</Button>
							</Item>
						</Form>
					</div>
				);
			case 5:
				return (
					<div className="handlingProcess_button_Popover">
						<Form onFinish={onFinishDelegateOpen} layout="vertical">
							<Item label={t(`${en_vi}.recipient`)} name="delegateUserId" rules={[{ required: true }]}>
								<Select style={{ width: "100%" }} options={options} />
							</Item>
							<Item label={t(`${en_vi}.approvalOpinion`)} name="reason" rules={[{ required: true }]}>
								<TextArea rows={4} />
							</Item>
							<Item className="button">
								<Button type="primary" htmlType="submit">
									{t(`${en_vi}.delegate`)}
								</Button>
								<Button onClick={cancel}>{t(`${en_vi}.cancel`)}</Button>
							</Item>
						</Form>
					</div>
				);
			case 6:
				return (
					<div className="handlingProcess_button_Popover">
						<Form onFinish={onFinishCountersignOpen} layout="vertical">
							<Item label={t(`${en_vi}.signatureProcessingPerson`)} name="userIds" rules={[{ required: true }]}>
								<Select mode="multiple" allowClear style={{ width: "100%" }} placeholder="Please select" options={options} />
							</Item>
							<Item label={t(`${en_vi}.approvalOpinion`)} name="reason" rules={[{ required: true }]}>
								<TextArea rows={4} />
							</Item>
							<Item className="button">
								<Button type="primary" htmlType="submit">
									{t(`${en_vi}.countersign`)}
								</Button>
								<Button onClick={cancel}>{t(`${en_vi}.cancel`)}</Button>
							</Item>
						</Form>
					</div>
				);
			// case 7:
			// 	return (
			// 		<div className="handlingProcess_button_Popover">
			// 			<Form onFinish={onFinishReturnOpen} layout="vertical">
			// 				<Item label="退回节点" name="username" rules={[{ required: true }]}>
			// 					<Select
			// 						mode="multiple"
			// 						allowClear
			// 						style={{ width: "100%" }}
			// 						placeholder="Please select"
			// 						onChange={handleChange}
			// 						options={options}
			// 					/>
			// 				</Item>
			// 				<Item label="退回理由" name="reason" rules={[{ required: true }]}>
			// 					<TextArea rows={4} />
			// 				</Item>
			// 				<Item className="button">
			// 					<Button type="primary" htmlType="submit">
			// 						退回
			// 					</Button>
			// 					<Button onClick={cancel}>取消</Button>
			// 				</Item>
			// 			</Form>
			// 		</div>
			// 	);
			default:
				// return <></>;
				return (
					<div className="handlingProcess_button_Popover">
						<Form onFinish={onFinishCancelOpen} layout="vertical">
							<Item label={t(`${en_vi}.reasonForCancellation`)} name="reason" rules={[{ required: true }]}>
								<TextArea rows={4} />
							</Item>
							<Item className="button">
								<Button type="primary" htmlType="submit">
									{t(`${en_vi}.cancel`)}
								</Button>
								<Button onClick={cancel}>{t(`${en_vi}.cancel`)}</Button>
							</Item>
						</Form>
					</div>
				);
		}
	};
	//通过
	const handlePassThroughout = (newOpen: boolean) => {
		setPassThroughout(newOpen);
	};
	const onFinishPassThroughout = async (values: any) => {
		if (!record) return;
		values = {
			...values,
			id: record.id
		};
		const res = await todoApi.taskApprove(values);
		if (!res) return message.error(t(`${en_vi}.operationFailed`));
		message.success(t(`${en_vi}.operationSuccessful`));
		setPassThroughout(false);
		closeDrawer();
	};
	//拒绝
	const handleRefuse = (newOpen: boolean) => {
		setRefuse(newOpen);
	};
	const onFinishRefuse = async (values: any) => {
		if (!record) return;
		values = {
			...values,
			id: record.id
		};
		const res = await todoApi.taskReject(values);
		if (!res) return message.error(t(`${en_vi}.operationFailed`));
		message.success(t(`${en_vi}.operationSuccessful`));
		setRefuse(false);
		closeDrawer();
	};
	//抄送
	const handleMakeCopyFor = (newOpen: boolean) => {
		setMakeCopyFor(newOpen);
	};
	const onFinishMakeCopyFor = async (values: any) => {
		if (!record) return;
		values = {
			...values,
			id: record.id
		};
		const res = await todoApi.taskCopy(values);
		if (!res) return message.error(t(`${en_vi}.operationFailed`));
		message.success(t(`${en_vi}.operationSuccessful`));
		setMakeCopyFor(false);
		closeDrawer();
	};
	//转办
	const handleTransferOfficer = (newOpen: boolean) => {
		setTransferOfficer(newOpen);
	};
	const onFinishTransferOfficer = async (values: any) => {
		if (!record) return;
		values = {
			...values,
			id: record.id
		};
		const res = await todoApi.taskTransfer(values);
		if (!res) return message.error(t(`${en_vi}.operationFailed`));
		message.success(t(`${en_vi}.operationSuccessful`));
		setTransferOfficer(false);
		closeDrawer();
	};
	//委派
	const handleDelegateOpen = (newOpen: boolean) => {
		setDelegateOpen(newOpen);
	};
	const onFinishDelegateOpen = async (values: any) => {
		if (!record) return;
		values = {
			...values,
			id: record.id
		};
		const res = await todoApi.taskDelegate(values);
		if (!res) return message.error(t(`${en_vi}.operationFailed`));
		message.success(t(`${en_vi}.operationSuccessful`));
		setDelegateOpen(false);
		closeDrawer();
	};
	//加签
	const handleCountersignOpen = (newOpen: boolean) => {
		setCountersignOpen(newOpen);
	};
	const onFinishCountersignOpen = async (values: any) => {
		if (!record) return;
		values = {
			...values,
			id: record.id,
			type: "before"
		};
		const res = await todoApi.taskCreateSign(values);
		if (!res) return message.error(t(`${en_vi}.operationFailed`));
		message.success(t(`${en_vi}.operationSuccessful`));
		setCountersignOpen(false);
		closeDrawer();
	};
	// //退回
	// const handleReturnOpen = (newOpen: boolean) => {
	// 	setReturnOpen(newOpen);
	// };
	const onFinishReturnOpen = async () => {
		if (!record) return;
		const res = await todoApi.taskListByReturn(record.id);
		if (res.length === 0) return message.warning(t(`${en_vi}.there`));
		message.success(t(`${en_vi}.operationSuccessful`));
		setPassThroughout(false);
		closeDrawer();
	};
	//取消
	const handleCancelOpen = (newOpen: boolean) => {
		setCancelOpen(newOpen);
	};
	const onFinishCancelOpen = async (values: any) => {
		if (!record) return;
		values = {
			...values,
			id: record.id,
			type: "before"
		};
		const res = await todoApi.processInstanceCancelByStartUser(values);
		if (!res) return message.error(t(`${en_vi}.operationFailed`));
		message.success(t(`${en_vi}.operationSuccessful`));
		setCancelOpen(false);
		closeDrawer();
	};
	const cancel = () => {
		setPassThroughout(false);
	};
	const todoApiProcessInstance = async () => {
		if (!record) return;
		const id = record.processInstanceId ? record.processInstanceId : record.id;
		const res = await todoApi.processInstance(id);
		res.name = res.tasks[0].name;
		res.createTime = res.tasks[0].createTime;
		setProcess(res);
	};
	const getTaskListBy = async () => {
		const id = record.processInstanceId ? record.processInstanceId : record.id;
		const res = await todoApi.taskListByProcessInstanceId(id);
		setTaskListByProcess(res);
	};
	useEffect(() => {
		todoApiProcessInstance();
		getTaskListBy();
	}, [record]);
	useEffect(() => {
		todoApi.simpleList().then(res => {
			res = res.map((item: any) => {
				return {
					label: item.nickname,
					value: item.id
				};
			});
			setOptions(res);
		});
	}, []);
	return (
		<BasicDrawer showFooter={false} size="large" {...props} register={registerDrawer}>
			<div className="handlingProcess">
				<div className="handlingProcess_herder">
					<div className="handlingProcess_herder_top">
						<p>
							{t(`${en_vi}.number`)}：{process.processInstance && process.processInstance.id}
						</p>
					</div>
					<section>
						<div className="section_top flex">
							{process.processInstance && <h1 className="margin_0">{process.processInstance.name}</h1>}
							{process.processInstance && process.processInstance.status === 1 ? (
								<Tag color="processing"> {t(`${en_vi}.inApproval`)}</Tag>
							) : (
								""
							)}
							{process.processInstance && process.processInstance.status === 2 ? (
								<Tag color="success">{t(`${en_vi}.approved`)}</Tag>
							) : (
								""
							)}
							{process.processInstance && process.processInstance.status === 3 ? (
								<Tag color="error">{t(`task.processInstance.notApproved`)}</Tag>
							) : (
								""
							)}
						</div>
						<div className="section_name flex">
							<div className="section_name_left flex">
								<Avatar icon={<Icon icon="ant-design:user-outlined" />} />
								{process.processInstance && <p className="margin_0">{process.processInstance?.startUser.nickname}</p>}
							</div>
							{process && (
								<p className="margin_0">
									{formatDate(new Date(process.createTime))} {t(`${en_vi}.submit`)}
								</p>
							)}
						</div>
					</section>
				</div>
				{record && <Tabs defaultActiveKey="1" items={items}></Tabs>}
				{pageButton()}
			</div>
		</BasicDrawer>
	);
};
export default index;
